package group2.beans;

import group2.core.database.DatabaseUtil;
import group2.core.database.IJpaCtrl;
import group2.core.database.JpaCtrlFactory;
import group2.core.entities.CamelUser;
import java.io.Serializable;
import javax.ejb.Stateful;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

/**
 * Used for adding users
 * 
 * @author cnilsson
 */
@ManagedBean
@RequestScoped
@Stateful
public class AddUserControllerBean implements Serializable{
    // ------------TO-DO--------------------------
    // Should send email with the username and password as a confirmation if it works

    @ManagedProperty(value = "#{addUserBackingBean}")
    private AddUserBackingBean aubb;
    
    private boolean successUserCreation = false;

    public void doCreateUser(ActionEvent e) {
        CamelUser cU = new CamelUser(0, aubb.getUserName(), aubb.getPassword(),
                aubb.getFirstName(), aubb.getLastName(), aubb.getEmail());
        IJpaCtrl<CamelUser> ctrl = JpaCtrlFactory.getInstance().getCamelUserCtrl();
        if (DatabaseUtil.getInstance().isUnique(aubb.getUserName(), aubb.getEmail())) {
            ctrl.create(cU);
            successUserCreation = true;
            aubb.setMessage("");

        } else //camelUser with the requested userName or email allready exsist in the database
        {
            System.out.println("----Cant create User, not unique UserName and/or email---");
            aubb.setMessage("User can't be created, choose another email or username.");
        }

    }
    
    public String navigate(){
        if(successUserCreation)
            return "onSuccessfulUserCreation";
        else
            return "onFailedUserCreation";   
    }
    
    public AddUserBackingBean getAubb() {
        return aubb;
    }

    public void setAubb(AddUserBackingBean aubb) {
        this.aubb = aubb;
    }

    /** Creates a new instance of AddUserControllerBean */
    public AddUserControllerBean() {
    }
}
